<?php


namespace App\backend\models;


use App\common\models\BaseModel;
use DateTimeInterface;
use Illuminate\Support\Facades\DB;

class MemberGroupModel extends BaseModel
{
    // 表名
    const TABLE_NAME = "member_group";
    public $table = self::TABLE_NAME;


    /**
     * 关联 member 数据表 一对多
     */
    public function member()
    {
        return $this->hasMany(MemberModel::class, 'group_id', 'id');
    }

    /**
     * 获取会员分组列表
     */
    public static function getGroupPageList($params)
    {
        $keyword = isset($params['keyword'])?trim($params['keyword']):'';
        $where = [];
        if ($keyword){
          $where[] = ['group_name','like','%'.$keyword.'%'];
        }
        $page = !isset($params['page']) ? 1 : $params['page'];unset($params['page']);
        $limit = !isset($params['limit']) ? 10 : $params['limit'];unset($params['limit']);

        $result = self::query()->select(['id', 'group_name'])
            ->with(['member' => function($query){
                return $query->select(['uid','group_id']);
            }])->where($where)->paginate($limit, ['*'], 'page', $page)->toArray();

        return ['data'=>$result['data'],'total'=>$result['total']];

    }

    /**
     * 查询字段规则
     *
     * @return array
     */
    static public function rules()
    {
        return [
            'group_name' => 'required|string|max:45', // 会员分组名称
            'automatic_labeling' => 'integer', // 自动打标签
            'accumulated_transaction_amount' => 'numeric:2', // 累计交易金额
            'accumulated_transaction_orders' => 'integer', // 累计交易订单
            'current_points_greater' => 'integer', // 当前积分大于
            'current_balance' => 'numeric:2', // 当前余额大于
            'goods_ids' => 'string', // 购买指定商品id
        ];
    }

    /**
     * 字段验证返回错误信息
     *
     * @return array
     */
    static public function message()
    {
        return [
            'group_name.required' => '会员分组名称必填', // 会员分组名称
            'group_name.string' => '会员分组名称必须字符', // 会员分组名称
            'group_name.max' => '会员分组名称最大45位', // 会员分组名称
            'automatic_labeling.required' => '自动打标签必须整数', // 自动打标签
            'accumulated_transaction_amount.numeric' => '累计交易金额保留两位小数', // 累计交易金额
            'accumulated_transaction_orders.integer' => '累计交易订单必须整数', // 累计交易订单
            'current_points_greater.integer' => '当前积分大于必须整数', // 当前积分大于
            'current_balance.numeric' => '当前余额大于保留两位小数', // 当前余额大于
            'goods_ids.string' => '购买指定商品id必须字符', // 购买指定商品id
        ];
    }

    /**
     * 格式化时间
     * @param DateTimeInterface $date
     * @return mixed
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }


}

